//  SwiftDemo
//
//  Created by Chris on 2017/6/12.
//  Copyright © 2017年 chris. All rights reserved.
//

import UIKit
import SVProgressHUD

class CJMainViewController: UITabBarController {
    
    /// 定时显示未读消息数据
    fileprivate var timer: Timer?
    
    /// 加号按钮
    fileprivate lazy var composeBtn = UIButton.cj_init("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        delegate = self
        // 添加登录通知
        NotificationCenter.default.addObserver(self, selector: #selector(loginNoti), name: NSNotification.Name(rawValue: CJUserShouldLoginInNotification), object: nil)
        
        setupChildControllers()
        setupComposeBtn()
        setupTimer()
        setupWelcomeView()
    }
    
    /// 设置界面为横屏
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        get {
            return .portrait
        }
    }
    
    // MARK: -加号按钮事件
    /// 加号按钮事件
    @objc fileprivate func composeStatus() {
        // FIXME: There is a problem
        print("点击了加号compose按钮")
    }
    
    /// 接收到登录通知响应方法
    ///
    /// - Parameter noti: 通知
    func loginNoti(noti: Notification) {
        print("接收到通知=== \(noti)")
        
        // SVP提示框显示时间
        var time = DispatchTime.now()
        
        // token过期
        if noti.object != nil {
            // 设置SVP 类型
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "登录超时, 请重新登录")
            time = DispatchTime.now() + 1
        }
        DispatchQueue.main.asyncAfter(deadline: time) {
            // 修改回SVP 类型
            SVProgressHUD.setDefaultMaskType(.clear)
            let VC = UINavigationController(rootViewController: CJOAuthViewController())
            self.present(VC, animated: true, completion: nil)
        }
    }
    
    deinit {
        // 销毁计时器
        timer?.invalidate()
        // 移除登录通知
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - 设置界面
extension CJMainViewController {
    
    // MARK: -设置所有的子控制器
    /// 设置所有的子控制器
    fileprivate func setupChildControllers() {
        
        guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),
            let data = NSData(contentsOfFile: path),
            let vcArray = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String: Any]] else {
            return
        }
        var vcArrM = [UIViewController]()
        
        for dict in vcArray! {
            vcArrM.append(controller(dict: dict))
        }
        viewControllers = vcArrM
    }
    
    // MARK: -使用字典创建子控制器
    /// 使用字典创建子控制器
    ///
    /// - Parameter dict: 包含clsName, title, imageName
    /// - Returns: 子控制器
    private func controller(dict: [String: Any]) -> UIViewController {
        
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? CJBaseViewController.Type,
            let visitInfoDict = dict["visitInfo"] as? [String: String] else {
                return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.visitInfoDictionary = visitInfoDict
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named:"tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
        
        let nav = CJNavigationController(rootViewController: vc)
        return nav
    }
    
    // MARK: -设置加号按钮
    /// 设置加号按钮
    fileprivate func setupComposeBtn() {
        
        tabBar.addSubview(composeBtn)
        
        let count = CGFloat(childViewControllers.count)
        
        let w = tabBar.bounds.size.width / count
        
        composeBtn.frame = tabBar.bounds.insetBy(dx: w * 2, dy: 0)
        
        composeBtn.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
}

// MARK: - 配置欢迎和新特性界面
extension CJMainViewController {
    
    /// 设置欢迎界面
    fileprivate func setupWelcomeView() {
        
        // 未登录时不做处理
        if !CJNetworkManager.sharedManager.userLoginOn {
            return
        }
        
        // 加载欢迎界面或者新特性界面
        let v = isNewFeature ? CJNewFeatureView.newFeatureView() : CJWelcomeView.welcomeView()
        
        view.addSubview(v)
    }
    
    /// 是否显示新特性界面
    private var isNewFeature: Bool {
        
        // 获取当前版本号
        let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String ?? ""
        
        // 获取沙盒路径
        let path = ("version" as NSString).appendingDocumentDirectory() as String
        
        // 获取沙盒中的版本号
        let sandBoxVersion = (try? String(contentsOfFile: path)) ?? ""
        
        // 保存当前版本号
        _ = try? sandBoxVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        return currentVersion != currentVersion
    }
}

// MARK: - 计时器
extension CJMainViewController {
    
    // MARK: -设置计时器
    /// 设置计时器
    fileprivate func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }
    
    // MARK: -计时器请求
    /// 计时器请求
    @objc private func timerAction() {
        
        if !CJNetworkManager.sharedManager.userLoginOn {
            return
        }
        // 获取未读数量
        CJNetworkManager.unreadCount { (unreadCount) in
            
            print("获取到\(unreadCount)条新消息")
            
            var count = 0
            var bgValue: String? = ""
            
            if unreadCount <= 0 {
                count = 0
                bgValue = nil
            } else if unreadCount <= 99 {
                count = unreadCount
                bgValue = "\(unreadCount)"
            } else {
                count = 99
                bgValue = "99+"
            }
            // 首页tabbaritem设置数量
            UIApplication.shared.applicationIconBadgeNumber = count
            self.tabBar.items?[0].badgeValue = bgValue
        }
    }
}

// MARK: - 控制器跳转(控制加号按钮点击)
extension CJMainViewController: UITabBarControllerDelegate {
    
    /// 当点击中间加号按钮时, 不执行tabar控制器切换
    ///
    /// - Parameters:
    ///   - tabBarController: 当前tabbar控制器
    ///   - viewController: 将要跳转的控制器
    /// - Returns: 是否切换控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let currentIdx = selectedIndex
        let shouldIdx = (childViewControllers as NSArray).index(of: viewController)
        
        if shouldIdx == 0 && currentIdx == shouldIdx {
            print("点击了首页")
            
            let homeNav = childViewControllers[0] as! CJNavigationController
            let homeVC = homeNav.viewControllers.first as! CJBaseViewController
            
            homeVC.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                homeVC.loadData()
            })
            // 把App icon中的badge清空
            UIApplication.shared.applicationIconBadgeNumber = 0
            tabBar.items?[0].badgeValue = nil
        }
        return !viewController.isMember(of: UIViewController.self)
    }
}
